-module(virserver).

-export([start/0]).

-include("megaeyes.hrl").

start() ->
    register(?INFOSERVICE, spawn(fun() -> info:infomanager(init) end)),
    start_megaeyes_server().

loop() ->
    receive
	Msg ->
	    io:format("Main Process Recv ~p~n", [Msg]),
	    loop()
    end.

start_megaeyes_server() ->
    {ok,  Listen}  =  gen_tcp:listen(?PORT,  [binary,  {packet,  0}, {reuseaddr,  true}, {active,  true}]),
    spawn( fun() ->accept_peer(Listen) end),%must new spawn a process
    loop().

accept_peer(Listen) ->
    {ok,  Socket}  =  gen_tcp:accept(Listen),
    %spawn( fun() -> loop(Socket) end ), note: this is wrong,because recved msg will send to exec accept process rather than exec loop process
    spawn( fun() ->accept_peer(Listen) end),
    inet:setopts(Socket,[{packet,0},binary, {nodelay,true},{active,true}]),
    process(Socket,run,[]).    
    
process(Socket,continue,Buf) ->
    Ret = parser:splite_message(Buf),
    case Ret of
	{ok,all,Message,Rest} ->
	    %io:format("continue rest ~w~n", [Rest]),
	    PPid = self(),
	    spawn( fun() -> PPid ! handler:handle(Message) end ),
	    process(Socket,continue, [Rest]);
	{error,_Reason} ->
	    %io:format("continue error: ~w~n", [Reason]),
	    process(Socket,run, Buf)
    end;
process(Socket,run,Buf) ->
    receive
	{tcp, Socket, Bin}  ->
	    %io:format("Server recv ~w~n", [Bin]),
	    NewBuf = Buf ++ [Bin],%might have performance problem
	    process(Socket,continue, NewBuf);
	{tcp_closed, Socket} ->
	    io:format("Server  socket  closed~n"),
	    process(Socket,peerclose,[]);
	{response,Resp} ->
	    gen_tcp:send(Socket, Resp),
	    process(Socket,run,Buf);
	_Other ->
	    process(Socket,run,Buf)
    after 300000 ->
	    io:format("Server  recv timeout~n"),
	    process(Socket,recvtimeout,[])
    end;
process(Socket,Reason,_Buf) ->
    {Socket,Reason}.


